package com.toman.ui.work.workshop;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;
import com.toman.Interfaces.NewBaseUrl;
import com.toman.JavaBean.BeltlineEntity;
import com.toman.JavaBean.OperationorderAllMappingsDto;
import com.toman.JavaBean.SendworkOrderMappingEntity;
import com.toman.JavaBean.SendworkorderEntity;
import com.toman.R;
import com.toman.Util.IntentUtils;
import com.toman.Util.JsonUtils;
import com.toman.Util.StringUtils;
import com.toman.Util.ToastUtil;
import com.toman.Util.ViewUtil;
import com.toman.toolbar.ToolBarActivity;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Request;
import okhttp3.Response;

public class DispatchingChildChildInfActivity extends ToolBarActivity {
    SendworkorderEntity bean;
    int position;
    CommonAdapter<OperationorderAllMappingsDto> adapter;
    @BindView(R.id.lv)
    RecyclerView lv;
    List<OperationorderAllMappingsDto> list = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dispatching_child_child_inf);
        ButterKnife.bind(this);
        initToolBar("子派工单");
        initIntent();
        initView();
    }

    private void initView() {
        initAdapter();
        Intent i = new Intent();
        i.putExtra("bean", bean);
        setResult(1000, i);
        list.add(bean.getOperationorderAllMappings().get(position));
    }

    private void initAdapter() {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        lv.setLayoutManager(linearLayoutManager);


        adapter = new CommonAdapter<OperationorderAllMappingsDto>(this, R.layout.item_plan_dispatching, list) {
            @Override
            protected void convert(ViewHolder holder, OperationorderAllMappingsDto item, final int position) {
                holder.setText(R.id.tv_title, item.getOrderName());
                RecyclerView recyclerView = holder.getView(R.id.lv);
                holder.getView(R.id.rl_button).setVisibility(View.VISIBLE);
                holder.getView(R.id.btn_look_first).setOnClickListener(v -> lookFirst(item));
                holder.getView(R.id.btn_look_more).setOnClickListener(v -> lookMore(item));
                if ("3".equals(status)) {
                    holder.getView(R.id.iv_add).setVisibility(View.GONE);
                }
//                重复添加
//                item.setSendworkOrderMappings(new ArrayList<>());
                SendworkOrderMappingEntity bean = item.getSendworkOrderMappings().get(position);
//                bean.setReceiveStatus("0");
//                bean.setOrderId(item.getOrderId());
//                bean.setWorkCount(0L);
//                item.getSendworkOrderMappings().add(bean);
                BeltlineEntity beltlineEntity=new BeltlineEntity();
                beltlineEntity.setBeltlineName("请选择");
                if (!item.getBeltlineEntities().get(0).getBeltlineName().equals("请选择")){
                    item.getBeltlineEntities().add(0,beltlineEntity);}
                Map map=new HashMap();
                CommonAdapter<SendworkOrderMappingEntity> adapter1 = new CommonAdapter<SendworkOrderMappingEntity>(getApplicationContext(), R.layout.item_plan_dispatching_more, item.getSendworkOrderMappings()) {
                    @Override
                    protected void convert(ViewHolder holder, SendworkOrderMappingEntity item1, final int position) {

                        holder.setText(R.id.et_number, item1.getWorkCount() + "");

                        holder.getView(R.id.iv_del).setOnClickListener(v -> remove(item.getSendworkOrderMappings(), position, (CommonAdapter<SendworkOrderMappingEntity>) recyclerView.getAdapter(),map));
                        EditText editText = holder.getView(R.id.et_number);


                        ArrayAdapter<BeltlineEntity> adapter = new ArrayAdapter<BeltlineEntity>(getApplicationContext(), R.layout.dialog_item_beacon, item.getBeltlineEntities());
                        ;
                        Spinner spinner = holder.getView(R.id.sp);
                        spinner.setAdapter(adapter);
                        for (int i = 0; i < item.getBeltlineEntities().size(); i++) {
                            try {
                                if (item1.getBeltlineId()!=null){
                                    if (item1.getBeltlineId().equals(item.getBeltlineEntities().get(i).getId())) {
                                        spinner.setSelection(i);
                                        break;
                                    }}
                            } catch (Exception e) {

                            }
                        }

                        spinner.setSelected(false);
                        spinner.setSelected(false);
                        if ("3".equals(status)|| "1".equals(item1.getReceiveStatus())) {
                            ViewUtil.unedit(editText);
                            editText.setPadding(0, 15, 0, 0);
                            holder.getView(R.id.iv_del).setVisibility(View.GONE);
                            spinner.setVisibility(View.INVISIBLE);
                            holder.setText(R.id.tv_name, item1.getBeltlineName() + "");
                            holder.getView(R.id.tv_name).setVisibility(View.VISIBLE);
                        }
                        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                            @Override
                            public void onItemSelected(AdapterView<?> parent, View view, int position1, long id) {

                                BeltlineEntity entity = (BeltlineEntity) parent.getSelectedItem();

                                if (!entity.getBeltlineName().equals("请选择")) {
                                    if (map.containsKey(entity.getId())) {
                                        if (map.get(entity.getId()) != item1) {
                                            ToastUtil.error(getApplicationContext(), "同一工序不能重复选择产线");
                                            spinner.setSelection(0);
                                        }
                                    } else {
                                        item1.setBeltlineId(entity.getId());
                                        item1.setBeltlineName(entity.getBeltlineName());
                                        map.put(entity.getId(), item1);
                                    }
                                }


                            }

                            @Override
                            public void onNothingSelected(AdapterView<?> parent) {

                            }
                        });
                        BeltlineEntity selectedItem = (BeltlineEntity) spinner.getSelectedItem();
                        ToastUtil.print("test" + selectedItem.getBeltlineName());
                        editText.addTextChangedListener(new TextWatcher() {
                            @Override
                            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                            }

                            @Override
                            public void onTextChanged(CharSequence s, int start, int before, int count) {

                            }

                            @Override
                            public void afterTextChanged(Editable s) {
                                if (!StringUtils.isEmpty(editText.getText().toString())) {
                                    item1.setWorkCount(Long.valueOf(editText.getText().toString()));
                                } else {
                                    item1.setWorkCount(0L);
                                }

                            }
                        });
                    }
                };
                adapter1.notifyDataSetChanged();
                recyclerView.setAdapter(adapter1);
                recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
                holder.getView(R.id.iv_add).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        SendworkOrderMappingEntity bean = new SendworkOrderMappingEntity();
                        bean.setOrderId(item.getOrderId());
                        bean.setWorkCount(0L);
                        item.getSendworkOrderMappings().add(bean);
                        adapter1.notifyItemInserted(item.getSendworkOrderMappings().size());
                    }
                });

            }
        };
        lv.setAdapter(adapter);

        adapter.notifyDataSetChanged();
    }

    private void initIntent() {
        bean = (SendworkorderEntity) getIntent().getSerializableExtra("bean");
        position = getIntent().getIntExtra("position", 0);
        status = getIntent().getStringExtra("status");

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.toolbar_finish, menu);
        MenuItem menuItem = menu.findItem(R.id.menu_finish);
        if (status.equals("3")) {
            menuItem.setVisible(false);
        }
        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.menu_finish:
                        add();
                        break;
                }
                return false;
            }
        });

        return true;
    }

    private void remove(List<SendworkOrderMappingEntity> listM, int position, CommonAdapter<SendworkOrderMappingEntity> adapter1, Map map) {
        if (listM.size() == 1) {
            ToastUtil.makeText(getApplicationContext(), "至少需要一条产线");
            return;
        }
        if (listM.get(position).getBeltlineId()!=null){
            map.remove(listM.get(position).getBeltlineId());}
        listM.remove(position);
        adapter1.notifyItemRemoved(position);
        adapter1.notifyItemRangeChanged(position, listM.size());
//        adapter.notifyDataSetChanged();
    }
    public void add() {

        for (int j = 0; j < list.get(0).getSendworkOrderMappings().size(); j++) {
            SendworkOrderMappingEntity bean2 = list.get(0).getSendworkOrderMappings().get(j);
            if (Long.valueOf(0L).equals(bean2.getWorkCount())) {
                ToastUtil.makeText(getApplicationContext(), "子派工单派工数量不得为空或0");
                return;
            }
        }
        bean.getOperationorderAllMappings().set(position, list.get(0));

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("id", bean.getId() + "");
        map.put("orderId", list.get(0).getOrderId());
        map.put("mappings", list.get(0).getSendworkOrderMappings());


        String str = JsonUtils.obj2JsonString(map);
        OkHttpUtils
                .post(NewBaseUrl.workshop_sendworkorder_updatemappingsbyorderid)
                .headers("token", token)
                .headers("Content-Type", "application/json")
                .postJson(str)
                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String result, Request request, @Nullable Response response) {
                        Log.i("test", getClass().toString() + result);
                        JSONObject jsonObj = JSON.parseObject(result);
                        int code = jsonObj.getInteger("code");ViewUtil.lagout(code,getApplicationContext());

                        if (code == 0) {
                            ToastUtil.makeText(getApplicationContext(), jsonObj.getString("msg"));
                            Intent i = new Intent();
                            i.putExtra("bean", bean);
                            setResult(1000, i);
                            finish();

                        } else {
                            ToastUtil.error(getApplicationContext(), jsonObj.getString("msg"));
                        }

                    }
                });
    }

    private void lookMore(OperationorderAllMappingsDto entity) {
        Bundle bundle = new Bundle();
        bundle.putString("isfirstReport", "0");
        bundle.putString("status", "1");
        try {
            bundle.putString("mappingId", entity.getSendworkOrderMappings().get(0).getId() + "");
            IntentUtils.startActivity(DispatchingChildChildInfActivity.this, SubmitActivity.class, bundle);
        } catch (Exception e) {
            e.printStackTrace();
            ToastUtil.error(getApplicationContext(),"暂无产线。");

        }
    }

    private void lookFirst(OperationorderAllMappingsDto entity) {
        Bundle bundle = new Bundle();
        bundle.putString("status", "1");
        bundle.putString("isfirstReport", "1");
        try {
            bundle.putString("mappingId", entity.getSendworkOrderMappings().get(0).getId() + "");
            IntentUtils.startActivity(DispatchingChildChildInfActivity.this, SubmitActivity.class, bundle);
        } catch (Exception e) {
            e.printStackTrace();
            ToastUtil.error(getApplicationContext(),"暂无产线。");

        }
    }

}